<template>
  <div class="app-container">
    <el-card>
      <!-- 顶部按钮栏 start -->
      <div class="btn-box flex justify-between mb-20">
        <div class="flex align-center">
          <el-input
            v-model="keyWords"
            placeholder="请输入关键词进行搜索"
            class="mr-5"
            clearable
            @clear="doSearch"
          ></el-input>
          <el-button type="primary" @click="doSearch">搜索</el-button>
        </div>
        <el-button type="primary" @click="toAddKeywords">新建关键词</el-button>
      </div>
      <!-- 顶部按钮栏 end -->

      <!-- 数据表格 start -->
      <PageTable :loading="loading" :data="dataSource" :columns="columns" :options="options" />
      <Pagination
        v-show="total > 0"
        :total="total"
        :pageNo.sync="listQuery.pageNo"
        :pageSize.sync="listQuery.pageSize"
        @pagination="getKeywordsList"
      />
      <!-- 数据表格 end -->
    </el-card>
  </div>
</template>

<script>
import { OPEN_PLATFORM, PLATFORM_COLOR } from '@/enum/goods.js'
export default {
  name: 'SearchKeywords',
  components: {},
  props: {},
  data() {
    return {
      // 搜索关键词
      keyWords: '',

      listQuery: {
        pageNo: 1,
        pageSize: 10
      },
      total: 0,

      // 表格加载
      loading: true,
      // 表格配置
      options: {
        border: true
      },
      // 表格列
      columns: [
        {
          prop: 'name',
          label: '关键词',
          render: (h, { row }) => {
            return <div style="color:#409eff; height:40px;line-height:40px;">{row.name}</div>
          }
        },
        { prop: 'clickNum', label: '点击数' },
        { prop: 'sort', label: '排序' },
        { prop: 'createdTime', label: '创建时间' },
        {
          label: '启用品牌',
          width: '100px',
          render: () => {
            return (
              <div class="flex flex-col">
                {Object.keys(OPEN_PLATFORM).map(el => (
                  <el-tag color={PLATFORM_COLOR[el]} style="color:#fff" class="mt-5">
                    {OPEN_PLATFORM[el]}
                  </el-tag>
                ))}
              </div>
            )
          }
        },
        {
          label: '启用状态',
          render: (h, { row }) => {
            return (
              <div>
                {Object.keys(OPEN_PLATFORM).map(el => (
                  <el-switch
                    class="mt-10"
                    value={row.platform.includes(el)}
                    active-text="启用"
                    inactive-text="隐藏"
                    active-color={PLATFORM_COLOR[el]}
                    inactive-color="#9b9b9f"
                    v-on:change={() => this.changeOpenStatus(row, el)}
                  ></el-switch>
                ))}
              </div>
            )
          }
        },
        {
          label: '操作',
          render: (h, { row }) => {
            return (
              <div>
                <el-link
                  underline={false}
                  type="primary"
                  class="ml-10 mr-10"
                  onClick={() => this.toAddKeywords(row)}
                >
                  编辑
                </el-link>
                {!row.openStatus ? (
                  <pop-confirm confirm={() => this.deleteKeywords(row)}>
                    <el-link type="primary" underline={false}>
                      删除
                    </el-link>
                  </pop-confirm>
                ) : (
                  ''
                )}
              </div>
            )
          }
        }
      ],
      // 表格源数据
      dataSource: []
    }
  },
  computed: {},
  watch: {},
  created() {
    // 获取关键词列表
    this.getKeywordsList()
  },
  mounted() {},
  methods: {
    // 获取关键词列表
    async getKeywordsList() {
      try {
        const {
          data: { records, total }
        } = await this.$http.goods.keywords.page({
          params: { ...this.listQuery, name: this.keyWords }
        })
        this.dataSource = records.map(el => {
          return { ...el, platform: el.platform.split(',') }
        })
        this.total = total
        this.loading = false
      } catch (error) {
        console.log('getKeywordsList', error)
      }
    },

    // 点击搜索
    doSearch() {
      this.listQuery.pageNo = 1
      this.getKeywordsList()
    },

    /**
     * 跳转新建/编辑关键词
     * @param {Object} item 行数据
     */
    toAddKeywords({ id }) {
      this.$router.push({ name: 'AddKeywords', query: { id } })
    },

    /**
     * 点击切换平台启用状态
     * @param {Object} item 行数据
     * @param {String} value 平台对应值 参考枚举
     */
    changeOpenStatus({ id, platform }, value) {
      // 是否启用
      const isOpen = platform.includes(value) ? true : false
      const message = isOpen ? '已隐藏' : '已启用'
      // 参数处理
      let enablePlatform = []
      if (isOpen) {
        enablePlatform = platform.filter(el => el !== value).join(',')
      } else {
        enablePlatform = [...platform, value].filter(el => el).join(',')
      }
      this.$http.goods.keywords
        .enablePlatform({ id, platform: enablePlatform })
        .then(res => {
          if (res.status === 200) {
            this.getKeywordsList()
            this.$message.success(message)
          }
        })
        .catch(err => {
          console.log('changeOpenStatus', err)
        })
    },

    /**
     * 删除关键词
     * @param {Object} item 行数据
     */
    deleteKeywords({ id }) {
      this.$http.goods.keywords
        .delete(id)
        .then(res => {
          if (res.status === 200) {
            this.getKeywordsList()
            this.$message.success('删除成功')
          }
        })
        .catch(err => {
          console.log('deleteKeywords', err)
        })
    }
  }
}
</script>

<style lang="scss" scoped></style>
